package com.suning.park.admin.mgr.reportform.controller;

import com.suning.park.dto.model.Coupon;
import com.suning.park.admin.exception.BusinessFailException;
import com.suning.park.admin.util.page.PageInfo;
import com.suning.park.admin.util.page.PageResult;
import com.suning.park.admin.base.BasicData;
import com.suning.park.admin.mgr.reportform.service.TicketUsedService;
import com.suning.park.admin.util.CheckValue;
import com.suning.park.admin.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

/*
 * Author:   niecheng
 * Date:     2017/1/16 18:48
 * Project:  park-pom
 * Description: 停车券用券数据模块
 */
@Controller
@RequestMapping(value = "/mgr/ticketUsed")
public class TicketUsedController implements BasicData {

    private static final Logger logger = LoggerFactory.getLogger(TicketUsedController.class);

    @Resource(name = "ticketUsedServiceImpl")
    protected TicketUsedService ticketUsedService;

    /**
     * 获取支付订单信息
     *
     * @param draw
     * @param pageInfo  分页信息
     * @param coupon 优惠券
     * @param startTimeStr 优惠券有效起始时间
     * @param endTimeStr 优惠券有效结束时间
     * @return
     */
    @RequestMapping(value = "/ajaxTicketUsedList")
    @ResponseBody
    public PageResult ajaxTicketUsedList(@RequestParam(value = "draw") int draw, PageInfo pageInfo, Coupon coupon, String startTimeStr, String endTimeStr) {
        final Coupon qCoupon = couponHandle(coupon, startTimeStr, endTimeStr);
        pageInfo = ticketUsedService.ajaxTicketUsedList(pageInfo, qCoupon);
        return new PageResult(pageInfo, draw);
    }

    /**
     * 优惠券查询条件处理
     * @param coupon
     * @param startTimeStr
     * @param endTimeStr
     * @return
     */
    public Coupon couponHandle(Coupon coupon, String startTimeStr, String endTimeStr){
        try{
            if (!CheckValue.isEmpty(coupon.getCouponName())) {
                coupon.setCouponName(new String(coupon.getCouponName().getBytes("ISO8859-1"), "UTF-8"));
            }
            if (!CheckValue.isEmpty(startTimeStr)) {
                final Date date = DateUtil.parseDateTime(startTimeStr, DateUtil.dateFormat);
                coupon.setStartTime(date);
            }
            if (!CheckValue.isEmpty(endTimeStr)) {
                final Date date = DateUtil.parseDateTime(endTimeStr, DateUtil.dateFormat);
                coupon.setEndTime(date);
            }
        }catch (Exception e){
            logger.error("参数处理异常，错误信息：{}", e.getMessage());
            throw new BusinessFailException("参数处理异常");
        }
        return coupon;
    }

    /**
     * 导出停车券使用数据
     * @param request
     * @param response
     * @param coupon 优惠券查询条件
     * @param startTimeStr 停车券有效起始时间
     * @param endTimeStr 停车券有效结束时间
     */
    @RequestMapping(value = "/exportTicketUsedList", method = RequestMethod.GET)
    public void exportTicketUsedList(HttpServletRequest request, HttpServletResponse response, Coupon coupon, String startTimeStr, String endTimeStr){
        ServletOutputStream outputStream = null;
        try {
            final Coupon curCoupon = couponHandle(coupon, startTimeStr, endTimeStr);
            byte[] bytes = ticketUsedService.exportTicketUsedList(curCoupon);
            response.setContentType("application/x-msdownload");
            response.setHeader("Content-Disposition", "attachment;filename=couPons.xls");
            response.setContentLength(bytes.length);
            outputStream = response.getOutputStream();
            outputStream.write(bytes);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("下载停车券使用数据出错, 错误信息：{ }",e);
        }finally {
            if(outputStream != null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    logger.info("输出流关闭失败，错误信息：{}", e.getMessage());
                }
            }
        }
    }

    @RequestMapping(value = "getDetail", method = RequestMethod.GET)
    public ModelAndView getDetail(ModelAndView view, String couponId) {
        logger.info("获取停车券使用数据明细");
        view.addObject("couponId", couponId);
        view.setViewName("reportForm/ticketUsed_detailed");
        return view;
    }

    /**
     * 获取明细
     * @param draw
     * @param pageInfo
     * @param state 券使用状态
     * @param couponId 券ID
     * @return
     */
    @RequestMapping(value = "/ajaxTicketUsedDetailedList")
    @ResponseBody
    public PageResult ajaxTicketUsedDetailedList(@RequestParam(value = "draw") int draw, PageInfo pageInfo, String state, String couponId) {
        pageInfo = ticketUsedService.ajaxTicketUsedDetailedList(pageInfo, state, couponId);
        return new PageResult(pageInfo, draw);
    }

    /**
     * 导出停车券使用明细
     * @param request
     * @param response
     * @param state 优惠券状态
     * @param couponId 优惠券ID
     */
    @RequestMapping(value = "/exportTicketUsedDetailed", method = RequestMethod.GET)
    public void exportTicketUsedDetailed(HttpServletRequest request, HttpServletResponse response, String state, String couponId){
        ServletOutputStream outputStream = null;
        try {
            byte[] bytes = ticketUsedService.exportTicketUsedDetailed(state, couponId);
            response.setContentType("application/x-msdownload");
            response.setHeader("Content-Disposition", "attachment;filename=couPonsDetail.xls");
            response.setContentLength(bytes.length);
            outputStream = response.getOutputStream();
            outputStream.write(bytes);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("下载停车券使用明细出错, 错误信息：{ }",e);
        }finally {
            if(outputStream != null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    logger.info("输出流关闭失败，错误信息：{}", e.getMessage());
                }
            }
        }
    }

}
